package com.weir.quarkus.base.system.resource;

import com.weir.quarkus.base.system.entity.SysModule;
import com.weir.quarkus.base.system.entity.SysRole;
import com.weir.quarkus.base.system.entity.SysRoleModule;
import com.weir.quarkus.base.system.entity.SysUserRole;
import com.weir.quarkus.base.system.utils.VuePageUtil;
import com.weir.quarkus.base.system.vo.ResultDataVo;
import com.weir.quarkus.base.system.vo.RoleAddVo;
import com.weir.quarkus.base.system.vo.RoleMeduleVo;
import com.weir.quarkus.base.system.vo.VuePageListVo;
import io.quarkus.hibernate.orm.panache.PanacheEntityBase;
import io.quarkus.hibernate.orm.panache.PanacheQuery;
import io.quarkus.panache.common.Sort;
//import io.quarkus.qute.Location;
//import io.quarkus.qute.Template;
//import io.quarkus.qute.TemplateInstance;
import io.vertx.core.json.JsonObject;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.microprofile.openapi.annotations.tags.Tag;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.persistence.EntityManager;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 
 * @ClassName: SysUserResource
 * @Description: 后台角色API管理
 * @author weir
 * @date 2021年8月25日
 *
 */
@Tag(name = "角色管理")
@Path("/sys/role")
@ApplicationScoped
public class SysRoleResource {
	
	@GET
	@Path("getAll")
	public Response getAll() {
		List<SysRole> list = SysRole.findAll().list();
		return Response.ok().entity(new ResultDataVo<>(200, "ok" , list)).build();
	}
	@Path("role/{id}")
	@POST
	@Transactional
	public Response add(@PathParam("id") Integer id) {
		SysRoleModule.delete("role_id", id);
		SysRole.deleteById(id);
		return Response.ok().entity(new ResultDataVo<>(200, "ok" , null)).build();
	}
	
	@Path("role/menu")
	@POST
	@Transactional
	public Response add(RoleMeduleVo roleAddVo) {
		SysRoleModule.delete("role_id", roleAddVo.roleId);
		
		String[] split = roleAddVo.moduleIds.split(",");
		for (String mId : split) {
			SysRoleModule roleModule = new SysRoleModule(roleAddVo.roleId, Integer.valueOf(mId));
			roleModule.persist();
		}
		return Response.ok().entity(new ResultDataVo<>(200, "ok" , null)).build();
	}
	
	@GET
	@Path("role/list")
	public Response listVue(@QueryParam("page") Integer page, @QueryParam("pageSize") Integer pageSize) {
		PanacheQuery<PanacheEntityBase> panacheQuery = SysRole.findAll(Sort.descending("createTime")).page(page-1, pageSize);
		VuePageListVo<SysRole> list = VuePageUtil.toPage(panacheQuery, new VuePageListVo<SysRole>(), page, pageSize);
		addMenus(list.list);
		return Response.ok().entity(new ResultDataVo<>(200, "ok" , list)).build();
	}
	
	private void addMenus(List<SysRole> list) {
		List<Integer> roleIds = list.stream().map(SysRole::getId).collect(Collectors.toList());
		EntityManager entityManager = SysModule.getEntityManager();
		List resultList = entityManager.createNativeQuery("select rm.role_id, GROUP_CONCAT(distinct(m.id)) ids "
				+ " from sys_module m INNER JOIN sys_role_module rm on m.id = rm.module_id"
				+ " where rm.role_id in (:ids) GROUP BY rm.role_id").setParameter("ids", roleIds).getResultList();
		for (Object row : resultList) {
			Object[] cells = (Object[]) row;
			for (SysRole role : list) {
				if (role.id.equals(cells[0])) {
					role.menuKeys = Arrays.asList(cells[1].toString().split(",")).stream().map(Integer::parseInt).collect(Collectors.toList());
				}
			}
		}
	}
	
	@GET
	@Path("list")
	public Response list(@QueryParam("page") Integer page, @QueryParam("rows") Integer rows) {
		PanacheQuery<PanacheEntityBase> panacheQuery = SysRole.findAll().page(page-1, rows);
		return Response.status(Status.OK).entity(new JsonObject()
				.put("total", panacheQuery.count())
				.put("rows", panacheQuery.list())).build();
	}
	
//	@Location("admin/roleAdd.html")
//	Template roleAdd;

//	@GET
//	@Path("addUI")
//	@Produces(MediaType.TEXT_HTML)
//	public TemplateInstance roleAdd() {
//		return roleAdd.data("role", null);
//	}
	
	@POST
	@Transactional
	public Response add(RoleAddVo roleAddVo) {
		if (roleAddVo.id == null || roleAddVo.id <= 0) {			
			SysRole role = new SysRole();
			role.code = roleAddVo.code;
			role.name = roleAddVo.name;
			role.persist();
			addRoleModule(roleAddVo, role);
		}else {
			SysRole role = SysRole.findById(roleAddVo.id);
			if (role != null) {
				role.code = roleAddVo.code;
				role.name = roleAddVo.name;
				
				SysRoleModule.delete("role_id", role.id);
				
				addRoleModule(roleAddVo, role);
			}
		}
//		return Response.status(Status.OK).entity(new JsonObject().put("msg", "添加或修改成功")).build();
		return Response.ok().entity(new ResultDataVo<>(200, "提交成功" , null)).build();
	}
	@POST
	@Path("role")
	@Transactional
	public Response addVue(RoleAddVo roleAddVo) {
		if (roleAddVo.id == null || roleAddVo.id <= 0) {			
			SysRole role = new SysRole();
			role.code = roleAddVo.code;
			role.name = roleAddVo.name;
			role.remark = roleAddVo.remark;
			role.persist();
			addRoleModule(roleAddVo, role);
		}else {
			SysRole role = SysRole.findById(roleAddVo.id);
			if (role != null) {
				role.code = roleAddVo.code;
				role.name = roleAddVo.name;
				role.remark = roleAddVo.remark;
				SysRoleModule.delete("role_id", role.id);
				
				addRoleModule(roleAddVo, role);
			}
		}
		return Response.ok().entity(new ResultDataVo<>(200, "ok" , null)).build();
	}

	private void addRoleModule(RoleAddVo roleAddVo, SysRole role) {
		if (StringUtils.isNotBlank(roleAddVo.moduleIds)) {
			String[] split = StringUtils.split(roleAddVo.moduleIds, ",");
			List<SysRoleModule> list = new ArrayList<>();
			for (String str : split) {
				SysRoleModule roleModule = new SysRoleModule(role.id, Integer.valueOf(str));
				list.add(roleModule);
			}
			SysRoleModule.persist(list);
		}
	}
	
//	@GET
//	@Path("editUI/{id}")
//	@Produces(MediaType.TEXT_HTML)
//	public TemplateInstance userEdit(@PathParam("id") Integer id) {
//		SysRole role = SysRole.findById(id);
//		if (role == null) {
//			return roleAdd.data("role", null);
//		}
//		List<SysRoleModule> roleModules = SysRoleModule.find("role_id", id).list();
//		List<Integer> moduleIds = roleModules.stream().map(SysRoleModule::getModuleId).collect(Collectors.toList());
//
//		RoleAddVo roleAddVo = new RoleAddVo();
//		roleAddVo.id = id;
//		roleAddVo.code = role.code;
//		roleAddVo.name = role.name;
//		roleAddVo.moduleIds = StringUtils.join(moduleIds, ",");
//		return roleAdd.data("role", roleAddVo);
//	}
	
	@DELETE
	@Transactional
	public Response delete(RoleAddVo roleAddVo) {
		if (StringUtils.isNotBlank(roleAddVo.ids)) {			
			List<Integer> list = Arrays.asList(roleAddVo.ids.split(",")).stream().map(Integer::parseInt).collect(Collectors.toList());
			SysRole.delete("id IN (?1)", list);
			SysRoleModule.delete("roleId IN (?1)", list);
			SysUserRole.delete("roleId IN (?1)", list);
		}
//		return Response.status(Status.OK).entity(new JsonObject().put("msg", "删除成功")).build();
		return Response.ok().entity(new ResultDataVo<>(200, "删除成功" , null)).build();
	}
	
}
